<template>
    <div class="top-nav">
        <!-- 面包屑导航栏 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item to="/index">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-for="(v, i) in menuArr" :to="v.path" :key="i">{{v.name}}</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 头像部分 -->
        <div class="user">
            <span class="welcome">{{account}}</span>
            <el-dropdown @command="jump">
                <span class="el-dropdown-link">
                    <el-avatar icon="el-icon-user-solid" class="head" :src="imgUrl"></el-avatar>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="/account/personal">个人信息</el-dropdown-item>
                    <el-dropdown-item command="/login">退出登录</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
    </div>
</template>

<script>
import local from "@/utils/local.js";  //引入本地存储
import {userInfo} from "@/api/user.js";  //引入账号模块接口
    export default {
        data(){
            return {
                menuArr:[{name: "", path: ""}],  // 面包屑导航栏数据
                account: "",  //用户名
                imgUrl: "",  //头像
            }
        },

        methods:{
            // 点击头像跳转相应页面
            jump(url){
                if(url === "/login"){
                    local.clear();
                    this.$router.push("/login");
                }else{
                    this.$router.push(url);
                }
            },

            // 渲染面包屑导航
            render(){
                let arr = this.$route.matched.filter(v => v.meta.title)
                this.menuArr = arr.map(v => {
                    return {name: v.meta.title, path: v.path}
                })
            }
        },

        // 页面创建时渲染面包屑导航
        async created(){
            this.render();
            let res = await userInfo();
            this.account = "欢迎您！" + res.data.account;
            local.set("userInfo", res.data);  //将用户信息储存在本地存储
            this.imgUrl = res.data.imgUrl;

            this.$bus.$on("sedImgUrl", imgUrl => {  //接受头像参数
                this.imgUrl = imgUrl;
            })
        },

        watch:{
            // 面包屑导航栏数据
            "$route.path"( newval ){
                this.render();
            }
        }
    }
</script>

<style lang="less" scoped>
.top-nav{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 60px;

    // 头像部分
    .welcome{
        margin-right: 10px;
    }

    .head{
        cursor: pointer;
        vertical-align: middle;
    }
}
</style>